<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { VideoPlay, VideoPause, Plus, Download } from '@element-plus/icons-vue'
import { likeMusic } from '@/api/music'
import { saveAs } from 'file-saver'
import { usePlayerStore, useMusicStore, usePlaylistStore } from '@/store'
import defaultCover from '@/assets/cover.jpg'
import { baseURL } from '@/utils/request'

const playerStore = usePlayerStore()
const musicStore = useMusicStore()
const playlistStore = usePlaylistStore()

const props = defineProps({
  rank: {
    type: [Number, String],
    required: true
  },
  songName: {
    type: String,
    required: true
  },
  artist: {
    type: String,
    default: '未知歌手'
  },
  album: {
    type: String,
    default: '未知专辑'
  },
  duration: {
    type: [Number, String],
    default: 0
  },
  coverUrl: {
    type: String,
    default: ''
  },
  musicUrl: {
    type: String,
    default: ''
  },
  isLiked: {
    type: Boolean,
    default: false
  },
  songId: {
    type: [Number, String],
    required: true
  },
  tags: {
    type: Array,
    default: () => []
  },
  isActive: {
    type: Boolean,
    default: false
  }
})

// 状态
const isHovered = ref(false)
const liked = ref(props.isLiked)
const isSmallScreen = ref(false) // 新增：是否是小屏幕的标志

// 计算属性：实时获取是否喜欢状态
const isLiked = computed(() => liked.value)

// 修改计算属性：检查是否为当前选中的歌曲（不管是否播放）
const isCurrentSong = computed(() => 
  playerStore.currentSong.id === props.songId
)

// 计算当前歌曲是否正在播放
const isCurrentPlaying = computed(() => 
  isCurrentSong.value && playerStore.isPlaying
)

// 添加计算属性来处理封面URL
const coverSrc = computed(() => {
  return props.coverUrl ? `${baseURL}${props.coverUrl}` : defaultCover
})

// 格式化时长
const formatDuration = (seconds) => {
  if (!seconds) return '00:00'
  seconds = Number(seconds)
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 播放/暂停
const togglePlay = () => {
  if (isCurrentPlaying.value) {
    // 如果当前歌曲正在播放，则暂停
    playerStore.togglePlay() 
    // 不需要发送 emit，因为我们已经直接控制了播放状态
  } else {
    // 检查是否是同一首歌
    if (playerStore.currentSong.id === props.songId) {
      // 如果是同一首歌，只需恢复播放
      playerStore.togglePlay()
    } else {
      // 如果是不同的歌，则需要加载并播放新歌
      emit('play', { id: props.songId, playing: true })
    }
  }
}

// 喜欢/取消喜欢
const toggleLike = async () => {
  try {
    const response = await likeMusic(props.songId)
    if (response.status === 0) {
      // 修改本地状态
      liked.value = !liked.value
      
      // 成功提示
      ElMessage.success(liked.value ? '已添加到我喜欢的音乐' : '已从我喜欢的音乐中移除')
      
      try {
        // 使用musicStore更新全局状态
        musicStore.updateSongLikeStatus(props.songId, liked.value)
        
        // 检查是否为当前播放的歌曲，如果是，则同步更新 playerStore 中的状态
        if (playerStore.currentSong && playerStore.currentSong.id === props.songId) {
          playerStore.currentSong.isFavorite = liked.value ? 1 : 0
        }
        
        // 重新获取音乐列表以更新所有视图
        await musicStore.fetchAllMusic()
      } catch (innerError) {
        console.error('更新状态时出错:', innerError)
      }
    } else {
      ElMessage.error(response.message)
    }
  } catch (error) {
    console.error('喜欢操作失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

// 添加到播放列表
const addToPlaylist = () => {
  // 构建歌曲对象
  const song = {
    id: props.songId,
    title: props.songName,
    artist: props.artist,
    album: props.album,
    coverUrl: props.coverUrl,
    musicUrl: props.musicUrl,
    isFavorite: props.isLiked ? 1 : 0,
    duration: props.duration
  }
  
  // 添加到播放列表
  const result = playlistStore.addToPlaylist(song)
  
  // 提示结果
  if (result) {
    ElMessage.success(`已添加《${props.songName}》到播放列表`)
  } else {
    ElMessage.info(`《${props.songName}》已在播放列表中`)
  }
}

// 下载音乐
const downloadMusic = async () => {
  try {
    ElMessage.info(`开始下载《${props.songName}》`)
    
    // 直接使用完整URL获取音乐文件
    const response = await fetch(`${baseURL}${props.musicUrl}`)
    const blob = await response.blob()
    
    // 从URL中获取文件扩展名
    const extension = props.musicUrl.split('.').pop()
    
    // 使用原始扩展名保存文件
    saveAs(blob, `${props.songName}.${extension}`)
    
    ElMessage.success(`《${props.songName}》下载成功`)
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error(`《${props.songName}》下载失败`)
  }
}

// 新增点击整行的处理函数
const handleItemClick = () => {
  // 通知父组件该行被点击
  emit('select', props.songId)
}

const emit = defineEmits(['select', 'play'])

// 检测屏幕宽度的函数
const checkScreenSize = () => {
  isSmallScreen.value = window.innerWidth <= 768
}

// 在组件挂载时添加窗口大小改变的监听器
onMounted(() => {
  // 初始检查
  checkScreenSize()
  // 添加窗口大小改变事件监听
  window.addEventListener('resize', checkScreenSize)
})

// 在组件卸载时移除监听器
onUnmounted(() => {
  window.removeEventListener('resize', checkScreenSize)
})
</script>

<template>
  <div 
    class="song-item" 
    :class="{ 
      'is-active': isActive, 
      'is-playing': isCurrentPlaying,
      'is-current': isCurrentSong  // 添加新的CSS类标识当前选中歌曲
    }" 
    @mouseenter="isHovered = true" 
    @mouseleave="isHovered = false"
    @click="handleItemClick"
  >
    <div class="rank-number">
      <!-- 修改逻辑：总是显示播放/暂停按钮，但图标根据状态变化 -->
      <template v-if="isCurrentSong">
        <button class="play-btn" @click="togglePlay">
          <el-icon v-if="isCurrentPlaying">
            <video-pause />
          </el-icon>
          <el-icon v-else>
            <video-play />
          </el-icon>
        </button>
      </template>

      <template v-else-if="isHovered">
        <button class="play-btn" @click="togglePlay">
          <el-icon>
            <video-play />
          </el-icon>
        </button>
      </template>
      
      <template v-else>
        <span>{{ rank }}</span>
      </template>
    </div>
    
    <!-- 歌曲信息区域 -->
    <div class="song-content">
      <!-- 封面 -->
      <div class="cover">
        <img :src="coverSrc" alt="封面">
      </div>
      
      <!-- 歌曲信息 -->
      <div class="info">
        <div class="title-wrapper">
          <span class="title">{{ songName }}</span>
          <div class="tags">
            <span class="tag vip">VIP</span>
            <span class="tag mv">MV</span>
          </div>
        </div>
        <div class="artist">{{ artist }}</div>
      </div>
    </div>
    
    <!-- 专辑和额外操作 -->
    <div class="album-section">
      <div class="album">{{ album }}</div>
      
      <!-- 悬浮时显示的操作按钮 -->
      <div class="hover-actions" v-show="isHovered || isSmallScreen">
        <button class="action-btn add-to-playlist" title="添加到播放列表" @click.stop="addToPlaylist">
          <el-icon><Plus /></el-icon>
        </button>
        <button class="action-btn download" title="下载" @click.stop="downloadMusic">
          <el-icon><Download /></el-icon>
        </button>
      </div>
    </div>
    
    <!-- 喜欢和时长 -->
    <div class="operations">
      <button class="like-btn" :class="{ 'liked': isLiked }" @click="toggleLike">
        <svg v-if="isLiked" width="16" height="16" viewBox="0 0 24 24" fill="#ff4e4e">
          <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
        </svg>
        <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#909399" stroke-width="2">
          <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/>
        </svg>
      </button>
      <span class="duration">{{ formatDuration(duration) }}</span>
    </div>
  </div>
</template>

<style scoped>
.song-item {
  position: relative;
  display: flex;
  align-items: center;
  padding: 8px 10px;
  border-radius: 4px;
  transition: all 0.2s;
  height: 60px;
  border-bottom: 1px solid #f2f2f2;
  cursor: pointer;
}

.song-item:hover {
  background-color: #f5f5f5;
}

.song-item:hover::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 3px;
  background-color: #c20c0c;
}

.song-item.is-active, .song-item.is-playing {
  background-color: #fef0f0;
}

.song-item.is-active::before, .song-item.is-playing::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 3px;
  background-color: #c20c0c;
}

/* 序号样式 */
.rank-number {
  width: 30px;
  text-align: center;
  margin-right: 10px;
  color: #999;
  font-size: 16px;
}

.play-btn {
  color: #e60026;
  cursor: pointer;
  display: flex;
  justify-content: center;
  border: none;
}

.play-btn .el-icon {
  font-size: 18px;
}

.play-btn:hover {
  transform: scale(1.1);
  color: #ff4e4e;
}

/* 歌曲内容区域 */
.song-content {
  display: flex;
  align-items: center;
  flex: 3;
  min-width: 0;
  margin-right: 20px;
}

.cover {
  width: 40px;
  height: 40px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 10px;
}

.cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.info {
  flex: 1;
  min-width: 0;
}

.title-wrapper {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.title {
  font-size: 14px;
  color: #333;
  margin-right: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.song-item.is-playing .title {
  color: #c20c0c;
  font-weight: 500;
}

.tags {
  display: flex;
}

.tag {
  margin-right: 4px;
  padding: 0 4px;
  font-size: 10px;
  height: 14px;
  line-height: 14px;
  border: 1px solid;
  border-radius: 2px;
}

.tag.vip {
  color: #e5c787;
  border-color: #e5c787;
  background-color: #000;
}

.tag.sq {
  color: #ff9600;
  border-color: #ff9600;
}

.tag.mv {
  color: #e60026;
  border-color: #e60026;
}

.artist {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 专辑和额外操作 */
.album-section {
  flex: 2;
  display: flex;
  align-items: center;
  margin-right: 10px;
  position: relative;
}

.album {
  font-size: 12px;
  color: #999;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  flex: 1;
}

/* 悬浮时显示的操作按钮 */
.hover-actions {
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.action-btn {
  background: none;
  border: none;
  cursor: pointer;
  color: #909399;
  padding: 4px;
  margin-right: 8px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.action-btn:hover {
  background-color: rgba(144, 147, 153, 0.1);
  color: #ff4e4e;
}

.action-btn .el-icon {
  font-size: 16px;
}

/* 操作区域 */
.operations {
  display: flex;
  align-items: center;
  width: 100px;
  justify-content: flex-end;
}

.like-btn {
  background: none;
  border: none;
  cursor: pointer;
  margin-right: 15px;
  padding: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: transform 0.2s;
}

.like-btn:hover {
  transform: scale(1.10);
}

.like-btn.liked {
  color: #ff4e4e;
}

.like-btn .el-icon {
  font-size: 18px;
}

.duration {
  font-size: 12px;
  color: #999;
}

/* 添加当前歌曲的样式，即使不在播放 */
.song-item.is-current {
  background-color: rgba(236, 65, 65, 0.05);
}

.song-item.is-current .title {
  color: #c20c0c;
  font-weight: 500;
}

/* 播放中的样式可以更明显一些 */
.song-item.is-playing {
  background-color: rgba(236, 65, 65, 0.1);
}

/* 修改响应式样式 */
@media screen and (max-width: 768px) {
  .album-section {
    /* 不完全隐藏，而是保持最小尺寸但使内容不可见 */
    width: 0;
    overflow: visible; /* 允许子元素溢出显示 */
    padding: 0;
    margin: 0;
    /* 保持显示以便其子元素可以正常工作 */
    display: flex !important;
    position: relative;
  }
  
  .album {
    display: none; /* 只隐藏专辑名称 */
  }
  
  .hover-actions {
    position: absolute;
    right: 60px;
    top: 50%;
    transform: translateY(-50%);
    padding: 4px;
    border-radius: 4px;
    z-index: 10;
    /* 确保在小屏幕上总是可见 */
    display: flex !important;
  }
  
  .action-btn {
    margin-right: 5px;
    padding: 5px;
  }
  
  .action-btn .el-icon {
    font-size: 18px;
  }
}

@media screen and (max-width: 576px) {
  .cover {
    width: 30px;
    height: 30px;
  }
  
  /* 在更小的屏幕上调整位置 */
  .hover-actions {
    right: -10px;
    padding: 3px;
  }

  .tags {
    display: none;
  }
}

@media screen and (max-width: 380px) {
  .hover-actions {
    right: -35px;
  }
}

</style> 